﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wildweeds.SSO.Entity;

namespace Wildweeds.SSO.UserManager
{
    public class TokenManager
    {
        static List<TokenInfo> tokenList = null;

        static TokenManager()
        {
            tokenList = new List<TokenInfo>();
        }

        public static bool AddToken(TokenInfo entity)
        {
            tokenList.Add(entity);
            return true;
        }

        public static AuthResult ValidateToken(TokenInfo entity)
        {
            AuthResult result = new AuthResult() { ErrorMsg = "Token不存在"};
            TokenInfo existToken = tokenList.SingleOrDefault(t => t.tokenId == entity.tokenId);
            /*
                t.RemoteIp == entity.RemoteIp && 
                t.IsValid &&
                t.CreateTime.AddMinutes(2) > DateTime.Now
              */

            if (existToken != null)
            {
                #region 客户端IP不一致
                //if (existToken.RemoteIp != entity.RemoteIp)
                //{
                //    result.ErrorMsg = "客户端IP不一致";
                //}
                #endregion

                if (!existToken.IsValid)
                    result.ErrorMsg = "Token已被使用过";
                else if (existToken.CreateTime.AddMinutes(2) < DateTime.Now)
                    result.ErrorMsg = "Token已过期"+existToken.CreateTime.ToLongTimeString()+":"+DateTime.Now.ToLocalTime();
                else  //只有未被使用过，且在2分钟之验证的才正确返回用户
                {
                    existToken.IsValid = false;
                    result.User = UserManager.GetByUserName(existToken.UserName);
                    result.ErrorMsg = string.Empty;
                }                
            }          

            return result;
        }
    }
}
